<?php

namespace App\Lib;

/**
 * 通用工具类
 */
class Utils
{
    /**
     * 生成的唯一性key
     * @param string $str
     * @return string
    */
    public static function getFileKey($str)
    {
        return substr(md5(self::makeRandomString() . $str . time() . rand(0, 9999)), 8, 16);
    }

    /**
     * 生成随机字符串
     * @param string $length 长度
     * @return string 生成的随机字符串
     */
    public static function makeRandomString($length = 1)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i=0; $i<$length; $i++) {
            $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

    /**
     * 将数据转化为utf-8类型数据
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function characet($data)
    {
        if (!empty($data) && is_string($data)) {
            $fileType = mb_detect_encoding($data, array('UTF-8','GB2312','GBK','LATIN1','BIG5','CP936'));
            if ($fileType != 'UTF-8') {
                $data = mb_convert_encoding($data, 'UTF-8', $fileType);
            }
        }
        return $data;
    }

    /**
     * 判断IP格式是否正确
     * @param  [type]  $ip [description]
     * @return boolean     [description]
     */
    public static function isIP($ip)
    {
        return preg_match('%^127\.|10\.|192\.168|128\.128|172\.(1[6-9]|2|3[01])%', $ip);
    }

    /*
     * 对一个数组重新0~n排序
     *
    */
    public static function sortArray($array)
    {
        $newArray = [];
        foreach ($array as $key=>$value) {
            $newArray[] = $value;
        }
        return $newArray;
    }

    /**
     * 检测数据是否以0开头
     * @param  [type]  $str [description]
     * @return boolean      [description]
     */
    public static function zeroFirst($str)
    {
        if (preg_match('/^0.*/', $str)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据图片生成保存
     * @param string $image
     * @param string $imageName $imagePath=NULL, $imageAutoDatePath=1
     * return imageSrc;     //图片生成成功, 返回图片保存路经
     */
    public static function saveImage($image, $imageName, $imagePath=null, $imageAutoDatePath=1)
    {
        if (strstr($image, ",")) {
            $image = explode(',', $image);
            $image = $image[1];
        }

        if ($imagePath==null) {
            $path = "./".date("Ymd");
        } elseif ($imageAutoDatePath==1) {
            $path = $imagePath."/".date("Ymd", time());
        } else {
            $path = $imagePath;
        }
        if (!is_dir($path)) { //判断目录是否存在 不存在就创建
            mkdir($path, 0777, true);
        }
        if (!isset($imageName) || empty($imageName) || $imageName == "") {
            $imgName= date("YmdHis", time()).'.jpg';
        } else {
            $imgName= $imageName;
        }
        $imageSrc= $path."/". $imgName; //保存路径 + 图片名字
        $data = array();
        $data['ret'] = -1;
        $data['path'] = $path;
        $data['name'] = $imgName;
        $data['imgSrc'] = $imageSrc;

        $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
        if (!$r) {
            return $data;   //图片生成失败
        } else {
            $data['ret'] = 0;
            //支持加水印功能，看最老的平台版本

            return $data;   //图片生成成功
        }
    }


    /**
     * 读取图片base64编码数据
     * @param  [type]  $filename [文件路径]
     * @param  integer $base     [0、纯base64编码1、自动分割处理并加data文件头，2、自动分割处理]
     * @return [type]            [description]
     */
    public static function readImage($filename, $base = 0)
    {
        if (!is_file($filename)) {
            return false;
        }
        if (1 == $base) {
            $image_info = getimagesize($filename);
            $base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($filename)));
        } elseif (2 == $base) {
            $base64_image_content = chunk_split(base64_encode(file_get_contents($filename)));
        } else {
            $base64_image_content = base64_encode(file_get_contents($filename));
        }

        return $base64_image_content;
    }

    /**
     * 遍历文件夹
     * @param  [type] $dir [description]
     * @param  [type] $del [0-数组形式返回文件夹下所有文件，1-删除文件夹下所有文件及文件夹]
     * @return [type]      [description]
     */
    public static function forDir($dir, $del=0)
    {
        $files = array();
        //判断目录是否存在
        if (file_exists($dir)) {
            if (@$handle = opendir($dir)) { //注意这里要加一个@，不然会有warning错误提示：）
                while (($file = readdir($handle)) !== false) {
                    if ($file != ".." && $file != ".") { //排除根目录；
                        if (is_dir($dir."/".$file)) { //如果是子文件夹，就进行递归
                           //循环当前目录
                           $files[$file] = self::forDir($dir."/".$file, $del);
                        } else {
                            if ($del == 1) {
                                //删除文件
                                unlink($dir.'/'.$file);
                            } else {
                                // 将文件名存储到数组中
                                $files[] = ($file);
                            }
                        }
                    }
                }
                closedir($handle);
                if ($del == 1) {
                    //删除文件夹
                    if (rmdir($dir)) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return $files;
                }
            }
        }
    }

    /**
     * 返回当前文件夹下所有的文件夹
     * @param  [type] $dir [description]
     * @param  [type] $del [0-数组形式返回文件夹下所有文件，1-删除文件夹下所有文件及文件夹]
     * @return [type]      [description]
     */
    public static function getFolder($dir)
    {
        $folder = array();
        //判断目录是否存在
        if (file_exists($dir)) {
            if (@$handle = opendir($dir)) { //注意这里要加一个@，不然会有warning错误提示：）
                while (($file = readdir($handle)) !== false) {
                    if ($file != ".." && $file != ".") { //排除根目录；
                        if (is_dir($dir."/".$file)) { //如果是子文件夹，就进行递归
                            //循环当前目录
                            $folder[$file] = self::getFolder($dir.'/'.$file);
                        }
                    }
                }
                closedir($handle);
                return $folder;
            }
        } else {
            return  [];
        }
    }

    /**
     * 返回当前磁盘空间
     * @param  [type] $dir [description]
     * @return [type]      [description]
     */
    public static function get_disk_info($dir = '')
    {
        if (PHP_OS === 'Linux') {  //Linux
            if ($dir) {
                $disk = $dir;
            } else {
                $disk = explode('/', __DIR__);
                $disk = ('/'.$disk[1]);
            }


            $res = [];
            $res['disk_total'] = round(((disk_total_space($disk) / 1024) / 1024) / 1024, 2); //G
            $res['disk_free'] = round(((disk_free_space($disk) / 1024) / 1024) / 1024, 2); //G
            $res['disk_fper'] = round(($res['disk_free'] / $res['disk_total'])*100, 2).'%'; //磁盘可用率

            $res['disk_total_num'] = $res['disk_total'];
            $res['disk_free_num'] = $res['disk_free'];

            $res['disk_total'] = $res['disk_total'] . ' G ';
            $res['disk_free'] = $res['disk_free'] . ' G ';
        } elseif (PHP_OS === 'WINNT') { //windows
            $disk = substr(__DIR__, 0, 2);
            $res = [];
            $res['disk_total'] = round(((disk_total_space($disk) / 1024) / 1024) / 1024, 2); //G
            $res['disk_free'] = round(((disk_free_space($disk) / 1024) / 1024) / 1024, 2); //G
            $res['disk_fper'] = round(($res['disk_free'] / $res['disk_total'])*100, 2).'%'; //磁盘可用率
            $res['disk_total_num'] = $res['disk_total'];
            $res['disk_free_num'] = $res['disk_free'];


            $res['disk_total'] = substr($disk, 0, 1) .'盘 '. $res['disk_total'] . ' G ';
            $res['disk_free'] =  substr($disk, 0, 1) .'盘 '. $res['disk_free'] . ' G ';
        } else {
            $res =  ['disk_total'=>'-','disk_free'=>'-','disk_fper'=>'-'];
        }
        return $res;
    }


    /**
     * [将多维数组转为一维数组,并且将上一层的key连上下一层的val]
     * @param  [type] $array [description]
     * @return [type]        [description]
     */
    public static function getOneArray($array, $skey = '')
    {
        $result_array = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result_array = array_merge($result_array, self::getOneArray($value, $key));
            } else {
                if (!empty($skey)) {
                    $result_array[] = $skey.'/'.$value;
                } else {
                    $result_array[] = $value;
                }
            }
        }
        return $result_array;
    }

    /**
     * 验证十一位手机号是否正确
     * @param  [type] $mobile [description]
     * @return [type]         [description]
     */
    public static function checkMobile($mobile)
    {
        //正则验证手机号
        $result = preg_match("/^1[3456789]{1}\d{9}$/", $mobile);

        return $result;
    }

    /**
     * 验证十一位手机号是否正确
     * @param  [type] $mobile [description]
     * @return [type]         [description]
     */
    public static function checkEmail($email)
    {
        //正则验证手机号
        $result = preg_match('/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i', $email);

        return $result;
    }

    /**
     * 将二维数组，根据pid进行无限分类
     * @param  [type] $list [description]
     * @return [type]       [description]
     */
    public static function list_to_tree($list, $root = 0)
    {
        $tree = $packData = [];
        foreach ($list as $data) {
            $packData[$data["id"]] = $data;
        }
        foreach ($packData as $key => $val) {
            if ($val["pid"] == $root) {
                //代表跟节点, 重点一
                $tree[] = &$packData[$key];
            } else {
                //找到其父类,重点二
                $packData[$val["pid"]]["children"][] = &$packData[$key];
            }
        }
        return $tree;
    }

    /**
     * 将一个无限级数组，和一个二维数组，进行pid匹配
     * @param  [type] $department [description]
     * @param  [type] $staff      [description]
     * @return [type]             [description]
     */
    public static function depSetStaff($data = [], $staff = [])
    {
        foreach ($data as $key => &$value) {
            $isset = 0;
            //判断子集是否存在
            if (isset($value['children']) && (count($value['children']) > 0)) {
                $isset = 1;
                $value['children'] = self::depSetStaff($value['children'], $staff);
            }

            foreach ($staff as $skey => $svalue) {
                if ($value['id'] == $svalue['pid']) {
                    $data[$key]['children'][] = $svalue;
                    //将匹配到的数据删除
                    unset($staff[$skey]);
                    $isset = 1;
                }
            }
            if ($isset == 0) {
                unset($data[$key]);
            }
        }

        return $data;
    }

    /**
     * 将一个无限级数组，和一个二维数组，进行pid匹配
     * @param  [type] $department [description]
     * @param  [type] $staff      [description]
     * @return [type]             [description]
     */
    public static function depSetStaff2($data = [], $staff = [])
    {
        foreach ($data as $key => &$value) {

            //判断子集是否存在
            if (isset($value['children']) && (count($value['children']) > 0)) {
                $value['children'] = self::depSetStaff2($value['children'], $staff);
            } else {
                $value['children'] = [];
            }

            foreach ($staff as $skey => $svalue) {
                if ($value['id'] == $svalue['pid']) {
                    $data[$key]['children'][] = $svalue;
                    //将匹配到的数据删除
                    unset($staff[$skey]);
                }
            }
        }

        return $data;
    }

    /**
     * 将一个无限级数组，和一个二维数组，进行pid匹配
     * @param  [type] $department [description]
     * @param  [type] $staff      [description]
     * @return [type]             [description]
     */
    public static function reset_tree($data = [])
    {
        $return = [];
        foreach ($data as $key => &$value) {
            //判断子集是否存在
            if (isset($value['children']) && (count($value['children']) > 0)) {
                $value['children'] = self::reset_tree($value['children']);
            }
            $return[] = $value;
        }

        return $return;
    }

    public static function getNum($data = [], $keys, $field)
    {
        $array = [];
        foreach ($data as $key => $value) {
            $nums = 0;
            if (isset($value['children'])) {
                $numbers = self::getNum($value['children'], $keys, $field);
                foreach ($numbers as $nk=>$nv) {
                    if ($nv['pid'] == $value['id']) {
                        $nums = $nums + $nv['nums'];
                    }
                    $array[$nk]['nums'] = $nv['nums'];
                    $array[$nk]['pid'] = $nv['pid'];
                }
            }
            $array[$value[$keys]]['nums'] = $nums + $value[$field];
            $array[$value[$keys]]['pid'] = $value['pid'];
        }
        return $array;
    }


    /* 生成sign,验证数据 */
    public static function makeSignWechat($data, $k)
    {
        if (is_array($data)) {
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
            ksort($data);
            $data=json_encode($data);
        }
        $sign = $k . $data  . $k;
        $sign = strtoupper(md5(sha1($sign)));
        return $sign;
    }


    /**
     * 根据图片生成保存
     * @param string $image
     * @param string $imageName $imagePath=NULL, $imageAutoDatePath=1
     * return imageSrc;     //图片生成成功, 返回图片保存路经
     */
    public static function saveImages($image, $imageName, $imagePath=null, $imageAutoDatePath=0)
    {
        if (strstr($image, ",")) {
            $image = explode(',', $image);
            $imagedata = $image[1];
        } else {
            $imgdata = $image;
        }

        if ($imagePath == null) {
            $path = "./".date("Ymd");
        } elseif ($imageAutoDatePath == 1) {
            $path = $imagePath."/".date("Ymd", time());
        } else {
            $path = $imagePath;
        }

        if (!is_dir($path)) { //判断目录是否存在 不存在就创建
            mkdir($path, 0777, true);
        }
        if (!isset($imageName) || empty($imageName) || $imageName == "") {
            $imgName= date("YmdHis", time()).'.jpg';
        } else {
            $imgName= $imageName;
        }
        $imageSrc = $path."/". $imgName; //保存路径 + 图片名字
        $data = array();
        $data['ret'] = -1;
        $data['path'] = $path;
        $data['name'] = $imgName;
        $data['imgSrc'] = $imageSrc;

        $r = file_put_contents($imageSrc, base64_decode($imagedata));//返回的是字节数
        if (!$r) {
            return $data;   //图片生成失败
        } else {
            $data['ret'] = 0;

            return $data;   //图片生成成功
        }
    }
}
